package v1

import (
	"fmt"
	"ginblog/model"
	"ginblog/utils/errmsg"
	"ginblog/utils/validator"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
)
var code int
//添加用户
func AddUser(c *gin.Context)  {
	//1，查询用户是否存在
	var data model.User
	var msg string
	_ = c.ShouldBindJSON(&data)
	msg, code = validator.Validate(&data)
	fmt.Println(code)
	if code!=errmsg.SUCCSE {
		c.JSON(http.StatusOK,gin.H{
			"status":code,
			"message":msg,
		})
		return
	}

	code = model.CheckUser(data.Username)
	if code== errmsg.SUCCSE{
		//成功就写入
		model.CreateUser(&data)
	}
	if code == errmsg.ERROR_USERNAME_USED {
		code = errmsg.ERROR_USERNAME_USED
	}
	//前面的是网络传输的状态，不止200
	c.JSON(http.StatusOK,gin.H{
		"status":code,
		"message":errmsg.GetErrMsg(code),
	})
	//2，新增用户
}
//查询用户
//查询单个用户
func GetOneUser(c *gin.Context)  {
	id,_ := strconv.Atoi(c.Param("id"))
	data,code := model.GetUser(id)
	c.JSON(http.StatusOK,gin.H{
		"status":code,
		"data":data,
	})
}
//查询用户列表
func GetUserList(c *gin.Context)  {
	pageSize,_ := strconv.Atoi(c.Query("pageSize"))
	pageNum,_ := strconv.Atoi(c.Query("pageNum"))
	username := c.Query("username")
	if pageSize==0   {
		pageSize = -1
	}
	if pageNum==0 {
		pageNum = -1
	}
	data,count := model.GetUserList(username,pageSize,pageNum)
	code = errmsg.SUCCSE
	c.JSON(http.StatusOK,gin.H{
		"status":code,
		"data":data,
		"count":count,
		"message":errmsg.GetErrMsg(code),
	})
}
//编辑用户
func UpdateUser(c *gin.Context)  {
	var data model.User
	id,_ := strconv.Atoi(c.Param("id"))
	c.ShouldBindJSON(&data)
	code = model.CheckUpUser(id,data.Username)
	if code == errmsg.SUCCSE{
		model.UpdateUser(id,&data)
	}
	if code== errmsg.ERROR_USERNAME_USED {
		c.Abort()
	}

	c.JSON(http.StatusOK,gin.H{
		"status":code,
		"message":errmsg.GetErrMsg(code),
	})
}

//删除用户
func DeleteUser(c *gin.Context)  {
	id,_ := strconv.Atoi(c.Param("id"))

	code = model.DeleteUser(id)
	c.JSON(http.StatusOK,gin.H{
		"status":code,
		"message":errmsg.GetErrMsg(code),
	})
}